package com.chiwen.web.controller.ks;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chiwen.common.core.domain.AjaxResult;
import com.chiwen.common.core.domain.entity.SysPayway;
import com.chiwen.common.core.domain.entity.SysUser;
import com.chiwen.common.exception.job.TaskException;
import com.chiwen.common.utils.*;
import com.chiwen.common.utils.http.CommonHttp;
import com.chiwen.common.utils.http.HttpUtils;
import com.chiwen.common.utils.http.PayWayUtil;
import com.chiwen.common.utils.ip.IpUtils;
import com.chiwen.common.utils.ip.VbUtils;
import com.chiwen.common.utils.uuid.UUID;
import com.chiwen.ks.domain.*;
import com.chiwen.ks.service.KsPayService;
import com.chiwen.quartz.domain.SysJob;
import com.chiwen.quartz.service.ISysJobService;
import com.chiwen.system.domain.SysOrder;
import com.chiwen.system.service.ISysOrderService;
import com.chiwen.system.service.ISysPaywayService;
import com.chiwen.system.service.ISysUserService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Map;


@RestController
@RequestMapping("/ks")
public class KsApiController {
    private static final Logger logger = LogManager.getLogger("KsApiController");

    private String querypayUrl = "https://www.kuaishoupay.com/pay/order/pc/trade/query";


    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysPaywayService iSysPaywayService;

    @Autowired
    private ISysOrderService sysOrderService;


    @Autowired
    private ISysJobService jobService;
    @Autowired
    private KsPayService ksPayService;

    /**
     * 生成二维码订单
     */
    @PostMapping("/gener/order")
    public AjaxResult generOrder(@RequestBody Pay vo) {

        // 检查 回调地址
        if (!vo.getPayWay().equals("KS_EWM_A") && StringUtils.isEmpty(vo.getRetUrl())) {
            return AjaxResult.error("参数异常1006！");
        }


        // 验签 获取密钥
        String sysKey = VbUtils.validationSign(ServletUtils.getRequest());

        SysPayway sysPayway = iSysPaywayService.selectSysPaywayByWayCode(vo.getPayWay());
        if (sysPayway == null || sysPayway.getStatus().equals("0")) {
            return AjaxResult.error("参数异常1004！");
        }

        // 充值余额
        Integer money = vo.getMoney();
        if (money == 0) {
            return AjaxResult.error("参数异常1005！");
        }

        // 请求的地址
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());


        //  获取用户信息  检查余额是否足够
        SysUser user = iSysUserService.selectUserBySysKey(sysKey);
        if(!user.getStatus().equals("0")){
            return AjaxResult.error("商户状态异常");
        }

        if (BigDecimalUtil.compareTo(String.valueOf(vo.getMoney()), user.getRemaMoney()) == 1) {
            return AjaxResult.error("参数异常1005！");
        }


        AjaxResult result = AjaxResult.error("创建失败！");

        if (vo.getPayWay().equals("KS_ALI_Y")) {

            result = KS_Y(vo, ip, "ALIPAY");

        } else if (vo.getPayWay().equals("KS_WX_Y")) {

            result = KS_Y(vo, ip, "WECHAT");

        } else if (vo.getPayWay().equals("KS_EWM_A")) {

            result = KS_WEM(vo, ip);

        }

        create_sys_order(user, result, vo);



        return result;
    }


    /**
     * 快手支付 阿里原生 微信原生
     */
    public AjaxResult KS_Y(Pay vo, String ip, String payway) {
        String result = PayWayUtil.KS_H5_Pay(vo.getMoney(), vo.getToken(), ip, payway);
        KS_PC_PAY_Bo obj = JSONObject.parseObject(result, KS_PC_PAY_Bo.class);
        if (obj.getCode().equals("SUCCESS")) {
            //创建支付订单
            result = PayWayUtil.KS_PC_PAY_pay(obj.getMerchantId(), obj.getOutOrderNo(), ip, vo.getMoney(), payway);
            KS_H5_PAY_pay_Bo parseObject = JSONObject.parseObject(result, KS_H5_PAY_pay_Bo.class);
            if (parseObject.getResult().equals("SUCCESS")) {
                KS_H5_PAY_Main succ = parseObject.getGateway_pay_param();
                succ.setOut_order_no(obj.getOutOrderNo());
                return AjaxResult.success(succ);
            }
            return AjaxResult.error("创建失败！" + parseObject.getResult());
        }
        return AjaxResult.error("创建失败！" + obj.getResult());
    }


    /**
     * 快手支付 阿里 微信 公用二维码
     */
    public AjaxResult KS_WEM(Pay vo, String ip) {
        String result = PayWayUtil.KS_PC_PAY(vo.getMoney(), vo.getUserId(), ip);
        KS_PC_PAY_Bo obj = JSONObject.parseObject(result, KS_PC_PAY_Bo.class);

        if (obj.getCode().equals("SUCCESS")) {
            //创建支付订单
            result = PayWayUtil.KS_PC_PAY_pay(obj.getMerchantId(), obj.getOutOrderNo(), ip);
            KS_PC_PAY_pay_Bo parseObject = JSONObject.parseObject(result, KS_PC_PAY_pay_Bo.class);
            if (parseObject.getResult().equals("SUCCESS")) {
                parseObject.setMerchant_id(obj.getMerchantId());
                return AjaxResult.success(parseObject);
            }
            return AjaxResult.error("创建失败！" + parseObject.getResult());
        }
        return AjaxResult.error("创建失败！" + obj.getResult());
    }

    /**
     * 创建系统订单
     */
    public void create_sys_order(SysUser user, AjaxResult result, Pay vo) {


        // 请求的设备
        String oa = IpUtils.getOs(ServletUtils.getRequest());
        // 请求的地址
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        SysOrder sysOrder = new SysOrder();
        sysOrder.setMerchName(user.getUserName());
        sysOrder.setPayWay(vo.getPayWay());
        if (String.valueOf(result.get("code")).equals("200")) {
            sysOrder.setOrderStage("2");
            Map<String, String> data = JSON.parseObject(JSON.toJSONString(result.get("data")), Map.class);
            sysOrder.setMerchOrder(data.get("out_order_no"));
            String s ="sysKsOrderTask.orderStatus2('"+data.get("merchant_id")+"','"+data.get("out_order_no")+"','"+ip+"')";
            jobService.createJob(s,"0/10 * * * * ?");;
        } else {
            sysOrder.setOrderStage("0");
            sysOrder.setRemark(String.valueOf(result.get("msg")));
        }


        sysOrder.setOrderMoney(String.valueOf(vo.getMoney()));
        sysOrder.setUserIp(ip);
        sysOrder.setUserEqu(oa);
        sysOrder.setCallbackUrl(vo.getRetUrl());
        sysOrder.setDeptId(user.getDeptId());
        sysOrder.setCreateBy(String.valueOf(user.getUserId()));
        sysOrderService.insertSysOrder(sysOrder);

        SysPayway sysPayway = iSysPaywayService.selectSysPaywayByWayCode(vo.getPayWay());
        sysPayway.setOrderNum((Integer.parseInt(sysPayway.getOrderNum()) + 1) + "");
        iSysPaywayService.updateSysPayway(sysPayway);

        String remaMoney = BigDecimalUtil.subString(user.getRemaMoney(), String.valueOf(vo.getMoney()));
        user.setOrderNum((Integer.parseInt(user.getOrderNum()) + 1) + "");
        user.setRemaMoney(remaMoney);
        iSysUserService.updateUser(user);
    }



    /**
     * 查询订单状态
     **/
    @PostMapping("/gener/orderStatus2")
    public AjaxResult orderStatus2(@RequestBody PayOrder payOrder) {

        String s ="sysKsOrderTask.orderStatus('"+payOrder.getMerchantId()+"','"+payOrder.getOutOrderNo()+"','127.0.0.1')";
        jobService.createJob(s,"0/10 * * * * ?");
        return AjaxResult.success("");

    }

    /**
     * 查询订单状态
     **/
    @PostMapping("/gener/orderStatus")
    public AjaxResult orderStatus(@RequestBody PayOrder payOrder) {
        // 请求的地址
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        //头信息，多个头信息多次调用此方法即可
        String result = PayWayUtil.KS_Order_Query(payOrder.getMerchantId(), payOrder.getOutOrderNo(), ip);
        System.out.println(result);
        KS_QUERY_ORDER data = JSON.parseObject(result, KS_QUERY_ORDER.class);
        if (data.getCode().equals("SUCCESS")) {
            AjaxResult re = AjaxResult.success();
            re.put("order_state", data.getOrder_state());
            re.put("order_amount", data.getOrder_amount());
            return re;
        }
        return AjaxResult.error(String.valueOf(data.getMsg()));

    }

    /**
     * 查询订单状态
     **/
    @PostMapping("/gener/sendCallBack")
    public AjaxResult sendCallBack(@RequestBody  SysOrder sysOrder ) {
        Map<String, String> data = sysOrderService.sendCallBack(sysOrder);
        int count = sysOrder.getCallbackCount();
        sysOrder.setCallbackCount(++count);
        if(String.valueOf(data.get("code")).equals("200")){
            sysOrder.setCallbackStage("回调成功");
            sysOrderService.updateSysOrder(sysOrder);
        }

        return AjaxResult.success(String.valueOf(data.get("msg")));

    }


    @PostMapping("/gener/testCall")
    public AjaxResult testCall( String outOrderNo, String stage) {

        String code = "成功";
        return AjaxResult.success(code);

    }

}
